import {ExclamationCircleOutlined} from '@ant-design/icons';
import {message, Modal, Radio, Rate, Tag} from 'antd';
import React, {useState, useRef} from 'react';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {isSuccess} from "@/utils/utils";
import {OpReplyManager} from "@/services/api-functions";
import Avatar from "antd/es/avatar/avatar";

export interface ResourceListProps {
  type: 'RESOURCES' | 'WORKS' | 'ARTICLE' | 'COURSE' | 'DYNAMIC' | 'SERVICE' | 'REQUIREMENT' | 'CASES'
  level: 1 | 2
  isComment?: boolean
  title?: string
  secondList?: any[]
}


export const handleCommentsState = async (id: number, enabling: number, first: boolean, isComment: boolean = false) => {
  if (!id) return true;
  try {
    if (isSuccess((isComment ? (first
      ? await OpReplyManager.modReply({id, enabling})
      : await OpReplyManager.modSecReply({id, enabling})) : await OpReplyManager.modEvaluation({
      id,
      enabling
    }))?.code)) {
      message.success(enabling ? '启用成功' : '禁用成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

const CommentList: React.FC<ResourceListProps> = ({type, level, isComment = true, title, secondList = []}) => {

  const [state, setState] = useState<'ALL' | 'UP' | 'DOWN'>('ALL');
  const [countInfo, setCountInfo] = useState<{ ALL: number, UP: number, DOWN: number }>({ALL: 0, UP: 0, DOWN: 0});
  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: isComment ? '发布用户' : '买家',
      dataIndex: ['userDto', 'avatarUrl'],
      ellipsis: true,
      width: 130,
      hideInSearch: true,
      fixed: 'left',
      render: (dom, record) => <><Avatar src={record?.userDto?.avatarUrl}/>&nbsp;
        <span>{record?.userDto?.nickName}</span></>,
    },
    {
      title: '订单编号',
      dataIndex: 'orderId',
      ellipsis: true,
      hideInTable: isComment,
      hideInSearch: isComment,
      width: 120,
    },
    {
      title: title ?? '标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 120,
    },
    {
      title: `${isComment ? '评论' : '评价'}内容`,
      dataIndex: 'content',
      ellipsis: true,
      width: 300,
    },
    {
      title: '回复',
      dataIndex: 'teacherReply',//teacherReplyTime
      ellipsis: true,
      hideInTable: level==2,
      width: 170,
    },
    {
      title: '评分',
      dataIndex: 'scoreNum',
      ellipsis: true,
      hideInTable: isComment,
      hideInSearch: true,
      width: 220,
      render: (_, record) => <><Rate value={record.score ?? 0} allowHalf disabled/> {record.score ?? 0}分</>
    },
    {
      title: '状态',
      dataIndex: 'enabling',
      valueEnum: {
        1: {text: '启用中', status: 'Success'},
        0: {text: '已禁用', status: 'Error'},
      },
      width: 100,
      hideInSearch: true,
      hideInForm: true,
    }, {
      title: '获赞数',
      dataIndex: 'greatNum',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '回复数',
      dataIndex: 'replyNum',
      ellipsis: true,
      hideInSearch: true,
      hideInTable: !isComment || level==2,
      width: 120,
    },
    {
      title: '发布时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit" onClick={() => Modal.confirm({
          title: '提示',
          icon: <ExclamationCircleOutlined/>,
          content: <span>确定要{record.enabling ? '禁用' : '启用'} <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
          okText: record.enabling ? '禁用' : '启用',
          cancelText: '取消',
          onOk: async () => {
            if (await handleCommentsState(record?.id, record.enabling ? 0 : 1, level == 1, isComment)) {
              actionRef.current?.reload()
            }
          },
        })}>{record.enabling ? '禁用' : '启用'}</a>,
        isComment && level == 1 ?
          <a key="edit" href={`/comment/detail/${type}/${record?.id}`} target='_blank' rel="noreferrer">详情</a> : null
      ],
    },
  ];


  const queryContentList = async (params: any) => {
    return isComment
      ? await OpReplyManager.replyListQuery(params)
      : await OpReplyManager.evaluationListQuery(params)
  }

  const queryFirstReplayList = async (params: any) => {
    const res = isComment
      ? await OpReplyManager.replyCount(type)
      : await OpReplyManager.evaluationCount(type);

    if (isSuccess(res.code)) {
      const {all, use, del} = res.data;
      setCountInfo({ALL: all, UP: use, DOWN: del})
    }

    return await queryContentList(params);

  }


  return (
    <>
      <ProTable<any, any>
        headerTitle={level == 1 ? <Radio.Group value={state} onChange={(e) => {
          setState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? 0}</Radio.Button>
          <Radio.Button value='UP'>启用中 {countInfo?.UP ?? 0}</Radio.Button>
          <Radio.Button value='DOWN'>已禁用 {countInfo?.DOWN ?? 0}</Radio.Button>
        </Radio.Group> : <p>{title}</p>}
        actionRef={actionRef}
        rowKey="key"
        search={level == 1 ? {
          labelWidth: 120,
        } : false}
        request={async (params) => {

          if(level==1){
            const query = {...params, businessType: type}
            if (state !== 'ALL') {
              query.enabling = state === 'UP' ? 1 : 0
            }

            const {data: {data, total}, code}: any = await queryFirstReplayList(query);

            return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
          }
          return {data: secondList, success: true, total: secondList.length};
        }}
        columns={columns}
        scroll={{x: 1300}}
      />
    </>
  );
};

export default CommentList;
